package com.service;

import com.entity.Employee;
import com.repository.EmployeeInfoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Optional;

@Service
@Transactional
public class EmployeeInfoService {

    @Autowired
    private EmployeeInfoRepository employeeInfoRepository;

    /**
     * 保存员工信息
     *
     * @param employee 员工信息
     * @return 保存后的对象
     */
    public Employee save(Employee employee) {
        if (employee.getId() == null) {
            employee.setCreateTime(new Date());
        }
        employee.setUpdateTime(new Date());
        return employeeInfoRepository.save(employee);
    }

    /**
     * 根据ID删除员工信息
     *
     * @param id ID
     */
    public void deleteById(Integer id) {
        employeeInfoRepository.deleteById(id);
    }

    /**
     * 根据ID获取员工信息
     *
     * @param id ID
     * @return 员工信息
     */
    @Transactional(readOnly = true)
    public Optional<Employee> findById(Integer id) {
        return employeeInfoRepository.findById(id);
    }

    /**
     * 分页查询员工信息
     *
     * @param pageNum  页码
     * @param pageSize 每页数量
     * @return 员工信息分页数据
     */
    @Transactional(readOnly = true)
    public Page<Employee> findAll(int pageNum, int pageSize) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.by("id").descending());
        return employeeInfoRepository.findAll(pageable);
    }

    /**
     * 根据姓名查询员工信息
     *
     * @param name     姓名
     * @param pageNum  页码
     * @param pageSize 每页数量
     * @return 员工信息分页数据
     */
    @Transactional(readOnly = true)
    public Page<Employee> findByNameContaining(String name, int pageNum, int pageSize) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.by("id").descending());
        return employeeInfoRepository.findByNameContaining(name, pageable);
    }
}